package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.bill.domain.MaterialIOVo;
import com.ruoyi.bill.domain.ZnDepotHead;
import com.ruoyi.bill.domain.ZnDepotItem;
import com.ruoyi.bill.mapper.ZnDepotHeadMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.material.domain.ZnMaterialInitialStock;
import com.ruoyi.material.mapper.ZnMaterialInitialStockMapper;
import com.ruoyi.material.service.IZnMaterialInitialStockService;
import com.ruoyi.system.domain.BossReportVo;
import com.ruoyi.system.domain.ZnProfitHistory;
import com.ruoyi.system.mapper.ZnProfitHistoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ZnProfitDetailMapper;
import com.ruoyi.system.domain.ZnProfitDetail;
import com.ruoyi.system.service.IZnProfitDetailService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 统计利润明细Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-10-10
 */
@Service
public class ZnProfitDetailServiceImpl implements IZnProfitDetailService 
{
    @Autowired
    private ZnDepotHeadMapper znDepotHeadMapper;
    @Autowired
    private ZnProfitDetailMapper znProfitDetailMapper;
    @Autowired
    private ZnProfitHistoryMapper znProfitHistoryMapper;
    @Autowired
    private ZnMaterialInitialStockMapper znMaterialInitialStockMapper;

    /**
     * 查询统计利润明细
     * 
     * @param id 统计利润明细主键
     * @return 统计利润明细
     */
    @Override
    public ZnProfitDetail selectZnProfitDetailById(Long id)
    {
        return znProfitDetailMapper.selectZnProfitDetailById(id);
    }

    /**
     * 查询统计利润明细列表
     * 
     * @param znProfitDetail 统计利润明细
     * @return 统计利润明细
     */
    @Override
    public List<ZnProfitDetail> selectZnProfitDetailList(ZnProfitDetail znProfitDetail)
    {
        znProfitDetail.setTenantId(SecurityUtils.getTenantId());
        return znProfitDetailMapper.selectZnProfitDetailList(znProfitDetail);
    }
     /**
      * 查询统计利润明细记录数
      *
      * @param znProfitDetail 统计利润明细
      * @return 统计利润明细记录数
     */
    public Integer selectZnProfitDetailCount(ZnProfitDetail znProfitDetail){
        znProfitDetail.setTenantId(SecurityUtils.getTenantId());
        return znProfitDetailMapper.selectZnProfitDetailCount(znProfitDetail);
    }


    /**
     * 新增统计利润明细
     * 
     * @param znProfitDetail 统计利润明细
     * @return 结果
     */
    @Override
    public int insertZnProfitDetail(ZnProfitDetail znProfitDetail)
    {
       znProfitDetail.setTenantId(SecurityUtils.getTenantId());
        return znProfitDetailMapper.insertZnProfitDetail(znProfitDetail);
    }

    /**
     * 修改统计利润明细
     * 
     * @param znProfitDetail 统计利润明细
     * @return 结果
     */
    @Override
    public int updateZnProfitDetail(ZnProfitDetail znProfitDetail)
    {
        return znProfitDetailMapper.updateZnProfitDetail(znProfitDetail);
    }

    /**
     * 批量删除统计利润明细
     * 
     * @param ids 需要删除的统计利润明细主键
     * @return 结果
     */
    @Override
    public int deleteZnProfitDetailByIds(Long[] ids)
    {
        return znProfitDetailMapper.deleteZnProfitDetailByIds(ids);
    }

    /**
     * 删除统计利润明细信息
     * 
     * @param id 统计利润明细主键
     * @return 结果
     */
    @Override
    public int deleteZnProfitDetailById(Long id)
    {
        return znProfitDetailMapper.deleteZnProfitDetailById(id);
    }

    @Override
    public List<BossReportVo> selectBossReportList(ZnProfitDetail znProfitDetail) {
        return znProfitDetailMapper.selectBossReportList(znProfitDetail);
    }
    @Transactional(rollbackFor = Exception.class)
    public void test(ZnDepotHeadMapper znDepotHeadMapper, ZnProfitDetailMapper znProfitDetailMapper, ZnProfitHistoryMapper znProfitHistoryMapper, IZnMaterialInitialStockService znMaterialInitialStockService, ZnDepotHead queryParam, Long profitId, Long tenanId){
        try {

            boolean flag = !Thread.currentThread().isInterrupted();
            if(flag){
                String threadName = Thread.currentThread().getName();
                System.out.println(threadName + " is running");
                queryParam.setTenantId(tenanId);
                queryParam.setDeleteFlag("0");
                //查询销售单
                queryParam.setType("出库");
                queryParam.setSubType("销售");
                queryParam.setStatus("2");
                //todo 临时使用
                //        queryParam.getParams().put("endOperTime",DateUtils.getTime());
                queryParam.getParams().put("endOperTime","2022-06-30 23:59:59");
                queryParam.getParams().put("orderSort","asc");
                List<ZnDepotHead> znDepotHeadList = znDepotHeadMapper.selectZnDepotHeadList(queryParam);
                List<ZnProfitDetail> dataList = new ArrayList<ZnProfitDetail>();
                Map<String, ZnMaterialInitialStock> initStockMap = new HashMap<>();//初始库存数量
                List<String> saveKey = new ArrayList<>();
                List<String> redisKeyList = new ArrayList<>();
//            System.out.println(JSON.toJSONString(znDepotHeadList));
                //TODO  临时过滤掉不统计商品
                List<Long> lsMaterialIdList = new ArrayList<>();
//            lsMaterialIdList.add(198l);//TODO 没有采购商品 198
//            lsMaterialIdList.add(378l);//TODO 静腌西冷牛排 有初始库存,没采购记录，如何处理？
//            lsMaterialIdList.add(556l);//TODO 礼盒包装 报溢入库，没采购记录，如何处理？
//            lsMaterialIdList.add(395l);//TODO 395 海霸王汤圆 有初始库存，没采购记录

                List<Long> nullStockMaterialIdList = new ArrayList<>();
                Map<String,List<MaterialIOVo>> materialMap = new HashMap<>();
                ZnProfitDetail znProfitDetail = new ZnProfitDetail();
                znProfitDetail.setTenantId(tenanId);
                for (ZnDepotHead znDepotHead:znDepotHeadList) {
                    if(flag){
                        ZnDepotItem znDepotItemQuery = new ZnDepotItem();
                        znDepotItemQuery.setHeaderId(znDepotHead.getId());
                        znDepotItemQuery.setTenantId(znDepotHead.getTenantId());
                        List<ZnDepotItem> itemList = znDepotHeadMapper.selectZnDepotItemList(znDepotItemQuery);
                        for (ZnDepotItem znDepotItem:itemList) {
//                        if(flag && znDepotItem.getBasicNumber().compareTo(BigDecimal.ZERO)>0 && znDepotHead.getId() ==395 && znDepotItem.getId()==7463){
                            if(flag && znDepotItem.getBasicNumber().compareTo(BigDecimal.ZERO)>0 ){
                                //1、判断商品是否在不统计的名单中、判断当前订单中的商品中已经计算过，就不在计算
                                if(lsMaterialIdList.contains(znDepotItem.getMaterialId()) || saveKey.contains(znDepotHead.getId()+"-"+znDepotItem.getId())){
                                    continue;
                                }
                                //TODO 多单位
                                if(znDepotItem.getUnitRatio()>1){//多单位，非基本单位

                                }else{
                                    znProfitDetail.setMaterialExtendId(znDepotItem.getMaterialExtendId());
                                    queryParam.getParams().put("materialExtendId",znDepotItem.getMaterialExtendId());
                                }
                                String initStockKey = znDepotItem.getDepotId()+"_"+znDepotItem.getMaterialId();
                                znProfitDetail = new ZnProfitDetail();
                                znProfitDetail.setProfitId(profitId);
                                znProfitDetail.setTenantId(tenanId);
                                znProfitDetail.setDepotId(znDepotItem.getDepotId());
                                znProfitDetail.setCustomerId(znDepotHead.getOrganId());
                                znProfitDetail.setMaterialId(znDepotItem.getMaterialId());
                                znProfitDetail.setMaterialExtendId(znDepotItem.getMaterialExtendId());
                                znProfitDetail.setOutHeadId(znDepotHead.getId());
                                znProfitDetail.setOutOperTime(znDepotHead.getOperTime());
                                znProfitDetail.setOutItemId(znDepotItem.getId());
                                znProfitDetail.setType(1);

                                //2、先看是否有初始库存，有的先扣初始库存
                                if(initStockMap.containsKey(initStockKey)){
                                    ZnMaterialInitialStock initStock = initStockMap.get(initStockKey);
                                    znProfitDetail.setInitStockId(initStock.getId());
                                    if(initStock.getNumber().compareTo(BigDecimal.ZERO)>0){
                                        int compareResult = znDepotItem.getBasicNumber().compareTo(initStock.getNumber());
                                        if(compareResult<=0){//订单数据小于等于初始库存，将扣除的剩余继续保存到map中
                                            znProfitDetail.setBasicNumber(znDepotItem.getBasicNumber());
                                            znProfitDetail.setOutPrice(znDepotItem.getBasicNumber().multiply(znDepotItem.getUnitPrice()));
                                            znProfitDetail.setInPrice(znDepotItem.getBasicNumber().multiply(initStock.getPrice()));
                                            initStock.setNumber(initStock.getNumber().subtract(znDepotItem.getBasicNumber()).abs());
                                            initStockMap.put(initStockKey,initStock);
                                            znDepotItem.setBasicNumber(BigDecimal.ZERO);
                                            continue;
                                        }else {//订单数量大于初始库存
                                            znProfitDetail.setBasicNumber(initStock.getNumber());
                                            znProfitDetail.setOutPrice(initStock.getNumber().multiply(znDepotItem.getUnitPrice()));
                                            znProfitDetail.setInPrice(initStock.getNumber().multiply(initStock.getPrice()));
                                            initStock.setNumber(BigDecimal.ZERO);
                                            initStockMap.put(initStockKey,initStock);
                                            znDepotItem.setBasicNumber(znDepotItem.getBasicNumber().subtract(initStock.getNumber()).abs());
                                        }
                                        znProfitDetail.setProfit(znProfitDetail.getOutPrice().subtract(znProfitDetail.getInPrice()));
                                        dataList.add(znProfitDetail);
                                    }
                                }else{
                                    ZnMaterialInitialStock znMaterialInitialStock = new ZnMaterialInitialStock();
                                    znMaterialInitialStock.setMaterialId(znDepotItem.getMaterialId());
                                    znMaterialInitialStock.setTenantId(tenanId);
                                    znMaterialInitialStock.setDeleteFlag("0");
                                    znMaterialInitialStock.setDepotId(znDepotItem.getDepotId());
                                    znMaterialInitialStock.getParams().put("gtNumber",0);//初始库存大于0
                                    List<ZnMaterialInitialStock> znMaterialInitialStockList =  znMaterialInitialStockService.selectZnMaterialInitialStockList(znMaterialInitialStock);
                                    if(znMaterialInitialStockList.size()>0){
                                        ZnMaterialInitialStock initStock = znMaterialInitialStockList.get(0);
                                        znProfitDetail.setInitStockId(initStock.getId());
                                        if(initStock.getPrice()==null){
                                            ZnProfitHistory znProfitHistory = new ZnProfitHistory();
                                            znProfitHistory.setId(profitId);
                                            znProfitHistory.setState(2);
                                            znProfitHistory.setResult(znDepotHead.getId()+"_"+znDepotItem.getId()+"—商品："+znDepotItem.getMaterialName()+"(货号:"+znDepotItem.getBarCode()+"）初始库存价格为空，请先填写上价格再重新计算");
                                            znProfitHistoryMapper.updateZnProfitHistory(znProfitHistory);
                                            Thread.currentThread().interrupt();
                                            System.out.println(threadName+"已中断0");
                                            flag = false;
                                            break;
                                        }
                                        int compareResult = znDepotItem.getBasicNumber().compareTo(initStock.getNumber());
                                        if(compareResult<=0){
                                            znProfitDetail.setBasicNumber(znDepotItem.getBasicNumber());
                                            znProfitDetail.setOutPrice(znProfitDetail.getBasicNumber().multiply(znDepotItem.getUnitPrice()));
                                            znProfitDetail.setInPrice(znProfitDetail.getBasicNumber().multiply(initStock.getPrice()));
                                            initStock.setNumber(initStock.getNumber().subtract(znDepotItem.getBasicNumber()).abs());
                                            initStockMap.put(initStockKey,initStock);
                                            znDepotItem.setBasicNumber(BigDecimal.ZERO);
                                        }else{
                                            znProfitDetail.setBasicNumber(initStock.getNumber());
                                            znProfitDetail.setOutPrice(initStock.getNumber().multiply(znDepotItem.getUnitPrice()));
                                            znProfitDetail.setInPrice(initStock.getNumber().multiply(initStock.getPrice()));
                                            initStock.setNumber(BigDecimal.ZERO);
                                            initStockMap.put(initStockKey,initStock);
                                        }
                                        znProfitDetail.setProfit(znProfitDetail.getOutPrice().subtract(znProfitDetail.getInPrice()));
                                        dataList.add(znProfitDetail);
                                    }
                                }
                                //3、当扣除初始库存之后，还有数量则从入库单据中，逐一进行扣。
                                if(znDepotItem.getBasicNumber().compareTo(BigDecimal.ZERO)>0){
                                    String key = "pandian_"+tenanId+"_"+znDepotItem.getMaterialId();
                                    List<MaterialIOVo> materialIOVos =  materialMap.get(key);
                                    if(materialIOVos ==null && !nullStockMaterialIdList.contains(znDepotItem.getMaterialId())){
                                        Map<String,Object> tempMap = znProfitDetailMapper.findLastOperTimeAndInId(znProfitDetail);
                                        if(tempMap !=null){
                                            if(tempMap.containsKey("in_head_id")){
                                                if(tempMap.get("in_head_id") !=null){
                                                    queryParam.getParams().put("gtId",Long.valueOf(tempMap.get("in_head_id").toString()));
                                                }
                                            }
                                        }
                                        queryParam.setType("入库");
//                                queryParam.setSubType("采购");
                                        queryParam.setStatus("2");//已入库
                                        queryParam.getParams().put("materialId",znDepotItem.getMaterialId());
                                        queryParam.getParams().put("depotId",znDepotItem.getDepotId());
                                        materialIOVos =  znDepotHeadMapper.selectMaterialPurchaseInList(queryParam);
                                    }
                                    if(materialIOVos == null ){
//                            System.out.println("库存不足订单："+JSON.toJSONString(znDepotHead));
//                            System.out.println("库存不足商品信息："+JSON.toJSONString(znDepotItem));
                                        ZnProfitHistory znProfitHistory = new ZnProfitHistory();
                                        znProfitHistory.setId(profitId);
                                        znProfitHistory.setState(2);
                                        znProfitHistory.setResult("商品："+znDepotItem.getMaterialName()+"("+znDepotItem.getBarCode()+"）库存不足，请先采购再重新计算");
                                        znProfitHistoryMapper.updateZnProfitHistory(znProfitHistory);
                                        Thread.currentThread().interrupt();
                                        System.out.println(threadName+"已中断1");
                                        flag = false;
                                        break;
                                        //                        return AjaxResult.error("商品："+znDepotItem.getMaterialName()+"("+znDepotItem.getBarCode()+"）库存不足，请先采购再继续计算");
                                    }else{
                                        Double orderNumber = znDepotItem.getBasicNumber().doubleValue();
                                        if (orderNumber > 0 ) {
//                                if (orderNumber > 0 ) {
                                            int nextIndex  = 0;
                                            for (int i=0;i<materialIOVos.size();i++){
                                                znProfitDetail = new ZnProfitDetail();
                                                znProfitDetail.setType(0);
                                                znProfitDetail.setProfitId(profitId);
                                                znProfitDetail.setTenantId(tenanId);
                                                znProfitDetail.setDepotId(znDepotItem.getDepotId());
                                                znProfitDetail.setCustomerId(znDepotHead.getOrganId());
                                                znProfitDetail.setMaterialId(znDepotItem.getMaterialId());
                                                znProfitDetail.setMaterialExtendId(znDepotItem.getMaterialExtendId());
                                                znProfitDetail.setOutHeadId(znDepotHead.getId());
                                                znProfitDetail.setOutOperTime(znDepotHead.getOperTime());
                                                znProfitDetail.setOutItemId(znDepotItem.getId());
                                                MaterialIOVo materialIOVo = materialIOVos.get(i);
                                                orderNumber = orderNumber - materialIOVo.getBasicNumber().doubleValue();
                                                if(orderNumber <= 0 ){
                                                    znProfitDetail.setInHeadId(materialIOVo.getInHeadId());
                                                    znProfitDetail.setInItemId(materialIOVo.getInItemId());
                                                    if(orderNumber==0){
                                                        znProfitDetail.setBasicNumber(materialIOVo.getBasicNumber());
                                                        nextIndex = i+1;
                                                    }else{//当商品的数量过多，修改为多余的数量
                                                        nextIndex = i;
                                                        znProfitDetail.setBasicNumber(materialIOVo.getBasicNumber().subtract(new BigDecimal(orderNumber)));
                                                        materialIOVo.setBasicNumber(new BigDecimal(orderNumber).abs());
                                                    }
                                                    znProfitDetail.setOutPrice(znDepotItem.getUnitPrice().multiply(znProfitDetail.getBasicNumber()));
                                                    znProfitDetail.setInPrice(znProfitDetail.getBasicNumber().multiply(materialIOVo.getUnitPrice()));
                                                    znProfitDetail.setProfit(znProfitDetail.getOutPrice().subtract(znProfitDetail.getInPrice()));
                                                    dataList.add(znProfitDetail);
                                                    saveKey.add(znProfitDetail.getOutHeadId()+"-"+znProfitDetail.getOutItemId());
                                                    break;
                                                }else{
                                                    if(i<materialIOVos.size()){
                                                        znProfitDetail.setBasicNumber(materialIOVo.getBasicNumber());
                                                        znProfitDetail.setInHeadId(materialIOVo.getInHeadId());
                                                        znProfitDetail.setInItemId(materialIOVo.getInItemId());
                                                        znProfitDetail.setOutPrice(znDepotItem.getUnitPrice().multiply(znProfitDetail.getBasicNumber()));
                                                        znProfitDetail.setInPrice(materialIOVo.getBasicNumber().multiply(materialIOVo.getUnitPrice()));
                                                        znProfitDetail.setProfit(znProfitDetail.getOutPrice().subtract(znProfitDetail.getInPrice()));
                                                        dataList.add(znProfitDetail);
                                                        saveKey.add(znProfitDetail.getOutHeadId()+"-"+znProfitDetail.getOutItemId());
                                                    }else{
                                                        //                                        return AjaxResult.error("商品："+znDepotItem.getMaterialName()+"("+znDepotItem.getBarCode()+"）库存不足，请先采购再继续计算");
                                                        ZnProfitHistory znProfitHistory = new ZnProfitHistory();
                                                        znProfitHistory.setId(profitId);
                                                        znProfitHistory.setState(2);
                                                        znProfitHistory.setResult("商品："+znDepotItem.getMaterialName()+"("+znDepotItem.getBarCode()+"）库存不足，请先采购再重新计算");
                                                        znProfitHistoryMapper.updateZnProfitHistory(znProfitHistory);
                                                        Thread.currentThread().interrupt();
                                                        System.out.println("商品："+znDepotItem.getMaterialName()+"("+znDepotItem.getMaterialId()+"）库存不足，请先采购再重新计算");
//                                                System.out.println(threadName+"已中断");
                                                        flag = false;
                                                        break;
                                                    }
                                                }
                                            }
                                            List<MaterialIOVo> temp = new ArrayList<>();
                                            if(nextIndex<materialIOVos.size()){
                                                temp =  materialIOVos.subList(nextIndex,materialIOVos.size());
                                                materialMap.put(key,temp);
                                            }else{
                                                nullStockMaterialIdList.add(znDepotItem.getMaterialId());
                                                materialMap.remove(key);
                                                System.out.println(key+","+nextIndex+","+ JSON.toJSONString(materialIOVos.subList(nextIndex,materialIOVos.size())));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if(flag){
                    int batchInsertCount = 0;
                    ZnProfitHistory znProfitHistory = new ZnProfitHistory();
                    znProfitHistory.setId(profitId);
                    System.out.println(JSON.toJSONString(dataList));
                    if(dataList.size()>0){
                        batchInsertCount =  znProfitDetailMapper.batchInsertZnProfitDetail(dataList);
                        if(initStockMap.size()>0){
                            for (Map.Entry<String,ZnMaterialInitialStock> entry:initStockMap.entrySet()) {
                                ZnMaterialInitialStock znMaterialInitialStock = new ZnMaterialInitialStock();
                                znMaterialInitialStock.setId(entry.getValue().getId());
                                znMaterialInitialStock.setIsProfit("1");
                                znMaterialInitialStockService.updateZnMaterialInitialStock(znMaterialInitialStock);
                            }
                        }
                        znProfitHistory.setResult("利润计算成功！");
                        znProfitHistory.setState(1);
                    }else{
//                return AjaxResult.success("没有有效的计算单据！");
                        znProfitHistory.setState(2);
                        znProfitHistory.setResult("没有有效的计算单据！");
                    }
                    znProfitHistoryMapper.updateZnProfitHistory(znProfitHistory);
                    Thread.currentThread().interrupt();
                    System.out.println(threadName + " is exit");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            ZnProfitHistory znProfitHistory = new ZnProfitHistory();
            znProfitHistory.setId(profitId);
            znProfitHistory.setState(2);
            znProfitHistory.setResult("计算异常，请联系管理员");
            znProfitHistoryMapper.updateZnProfitHistory(znProfitHistory);
            throw  new ServiceException("计算异常，请联系管理员");
        }
    }

    @Override
    public Map<String, Object> findLastOperTimeAndInId(ZnProfitDetail znProfitDetail) {
        return znProfitDetailMapper.findLastOperTimeAndInId(znProfitDetail);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void computeProfit(Long tenanId,Long profitId) {
        try {
            ZnDepotHead queryParam = new ZnDepotHead();
            boolean flag = !Thread.currentThread().isInterrupted();
            if(flag){
                String threadName = Thread.currentThread().getName();
                System.out.println(threadName + " is running");
                queryParam.setTenantId(tenanId);
                queryParam.setDeleteFlag("0");
                //查询销售单
                queryParam.setType("出库");
                queryParam.setSubType("销售");
                queryParam.setStatus("2");
                //todo 临时使用
                //        queryParam.getParams().put("endOperTime",DateUtils.getTime());
                queryParam.getParams().put("endOperTime","2022-06-30 23:59:59");
                queryParam.getParams().put("orderSort","asc");
                List<ZnDepotHead> znDepotHeadList = znDepotHeadMapper.selectZnDepotHeadList(queryParam);
                List<ZnProfitDetail> dataList = new ArrayList<ZnProfitDetail>();
                Map<String, ZnMaterialInitialStock> initStockMap = new HashMap<>();//初始库存数量
                List<String> saveKey = new ArrayList<>();
                List<String> redisKeyList = new ArrayList<>();
//            System.out.println(JSON.toJSONString(znDepotHeadList));
                //TODO  临时过滤掉不统计商品
                List<Long> lsMaterialIdList = new ArrayList<>();
//            lsMaterialIdList.add(198l);//TODO 没有采购商品 198
//            lsMaterialIdList.add(378l);//TODO 静腌西冷牛排 有初始库存,没采购记录，如何处理？
//            lsMaterialIdList.add(556l);//TODO 礼盒包装 报溢入库，没采购记录，如何处理？
//            lsMaterialIdList.add(395l);//TODO 395 海霸王汤圆 有初始库存，没采购记录

                List<Long> nullStockMaterialIdList = new ArrayList<>();
                Map<String,List<MaterialIOVo>> materialMap = new HashMap<>();
                ZnProfitDetail znProfitDetail = new ZnProfitDetail();
                znProfitDetail.setTenantId(tenanId);
                for (ZnDepotHead znDepotHead:znDepotHeadList) {
                    if(flag){
                        ZnDepotItem znDepotItemQuery = new ZnDepotItem();
                        znDepotItemQuery.setHeaderId(znDepotHead.getId());
                        znDepotItemQuery.setTenantId(znDepotHead.getTenantId());
                        List<ZnDepotItem> itemList = znDepotHeadMapper.selectZnDepotItemList(znDepotItemQuery);
                        for (ZnDepotItem znDepotItem:itemList) {
//                        if(flag && znDepotItem.getBasicNumber().compareTo(BigDecimal.ZERO)>0 && znDepotHead.getId() ==395 && znDepotItem.getId()==7463){
                            if(flag && znDepotItem.getBasicNumber().compareTo(BigDecimal.ZERO)>0 ){
                                //1、判断商品是否在不统计的名单中、判断当前订单中的商品中已经计算过，就不在计算
                                if(lsMaterialIdList.contains(znDepotItem.getMaterialId()) || saveKey.contains(znDepotHead.getId()+"-"+znDepotItem.getId())){
                                    continue;
                                }
                                //TODO 多单位
                                if(znDepotItem.getUnitRatio()>1){//多单位，非基本单位

                                }else{
                                    znProfitDetail.setMaterialExtendId(znDepotItem.getMaterialExtendId());
                                    queryParam.getParams().put("materialExtendId",znDepotItem.getMaterialExtendId());
                                }
                                String initStockKey = znDepotItem.getDepotId()+"_"+znDepotItem.getMaterialId();
                                znProfitDetail = new ZnProfitDetail();
                                znProfitDetail.setProfitId(profitId);
                                znProfitDetail.setTenantId(tenanId);
                                znProfitDetail.setDepotId(znDepotItem.getDepotId());
                                znProfitDetail.setCustomerId(znDepotHead.getOrganId());
                                znProfitDetail.setMaterialId(znDepotItem.getMaterialId());
                                znProfitDetail.setMaterialExtendId(znDepotItem.getMaterialExtendId());
                                znProfitDetail.setOutHeadId(znDepotHead.getId());
                                znProfitDetail.setOutOperTime(znDepotHead.getOperTime());
                                znProfitDetail.setOutItemId(znDepotItem.getId());
                                znProfitDetail.setType(1);

                                //2、先看是否有初始库存，有的先扣初始库存
                                if(initStockMap.containsKey(initStockKey)){
                                    ZnMaterialInitialStock initStock = initStockMap.get(initStockKey);
                                    znProfitDetail.setInitStockId(initStock.getId());
                                    if(initStock.getNumber().compareTo(BigDecimal.ZERO)>0){
                                        int compareResult = znDepotItem.getBasicNumber().compareTo(initStock.getNumber());
                                        if(compareResult<=0){//订单数据小于等于初始库存，将扣除的剩余继续保存到map中
                                            znProfitDetail.setBasicNumber(znDepotItem.getBasicNumber());
                                            znProfitDetail.setOutPrice(znDepotItem.getBasicNumber().multiply(znDepotItem.getUnitPrice()));
                                            znProfitDetail.setInPrice(znDepotItem.getBasicNumber().multiply(initStock.getPrice()));
                                            initStock.setNumber(initStock.getNumber().subtract(znDepotItem.getBasicNumber()).abs());
                                            initStockMap.put(initStockKey,initStock);
                                            znDepotItem.setBasicNumber(BigDecimal.ZERO);
                                            continue;
                                        }else {//订单数量大于初始库存
                                            znProfitDetail.setBasicNumber(initStock.getNumber());
                                            znProfitDetail.setOutPrice(initStock.getNumber().multiply(znDepotItem.getUnitPrice()));
                                            znProfitDetail.setInPrice(initStock.getNumber().multiply(initStock.getPrice()));
                                            initStock.setNumber(BigDecimal.ZERO);
                                            initStockMap.put(initStockKey,initStock);
                                            znDepotItem.setBasicNumber(znDepotItem.getBasicNumber().subtract(initStock.getNumber()).abs());
                                        }
                                        znProfitDetail.setProfit(znProfitDetail.getOutPrice().subtract(znProfitDetail.getInPrice()));
                                        dataList.add(znProfitDetail);
                                    }
                                }else{
                                    ZnMaterialInitialStock znMaterialInitialStock = new ZnMaterialInitialStock();
                                    znMaterialInitialStock.setMaterialId(znDepotItem.getMaterialId());
                                    znMaterialInitialStock.setTenantId(tenanId);
                                    znMaterialInitialStock.setDeleteFlag("0");
                                    znMaterialInitialStock.setDepotId(znDepotItem.getDepotId());
                                    znMaterialInitialStock.getParams().put("gtNumber",0);//初始库存大于0
                                    List<ZnMaterialInitialStock> znMaterialInitialStockList =  znMaterialInitialStockMapper.selectZnMaterialInitialStockList(znMaterialInitialStock);
                                    if(znMaterialInitialStockList.size()>0){
                                        ZnMaterialInitialStock initStock = znMaterialInitialStockList.get(0);
                                        znProfitDetail.setInitStockId(initStock.getId());
                                        if(initStock.getPrice()==null){
                                            ZnProfitHistory znProfitHistory = new ZnProfitHistory();
                                            znProfitHistory.setId(profitId);
                                            znProfitHistory.setState(2);
                                            znProfitHistory.setResult(znDepotHead.getId()+"_"+znDepotItem.getId()+"—商品："+znDepotItem.getMaterialName()+"(货号:"+znDepotItem.getBarCode()+"）初始库存价格为空，请先填写上价格再重新计算");
                                            znProfitHistoryMapper.updateZnProfitHistory(znProfitHistory);
                                            Thread.currentThread().interrupt();
                                            System.out.println(threadName+"已中断0");
                                            flag = false;
                                            break;
                                        }
                                        int compareResult = znDepotItem.getBasicNumber().compareTo(initStock.getNumber());
                                        if(compareResult<=0){
                                            znProfitDetail.setBasicNumber(znDepotItem.getBasicNumber());
                                            znProfitDetail.setOutPrice(znProfitDetail.getBasicNumber().multiply(znDepotItem.getUnitPrice()));
                                            znProfitDetail.setInPrice(znProfitDetail.getBasicNumber().multiply(initStock.getPrice()));
                                            initStock.setNumber(initStock.getNumber().subtract(znDepotItem.getBasicNumber()).abs());
                                            initStockMap.put(initStockKey,initStock);
                                            znDepotItem.setBasicNumber(BigDecimal.ZERO);
                                        }else{
                                            znProfitDetail.setBasicNumber(initStock.getNumber());
                                            znProfitDetail.setOutPrice(initStock.getNumber().multiply(znDepotItem.getUnitPrice()));
                                            znProfitDetail.setInPrice(initStock.getNumber().multiply(initStock.getPrice()));
                                            initStock.setNumber(BigDecimal.ZERO);
                                            initStockMap.put(initStockKey,initStock);
                                        }
                                        znProfitDetail.setProfit(znProfitDetail.getOutPrice().subtract(znProfitDetail.getInPrice()));
                                        dataList.add(znProfitDetail);
                                    }
                                }
                                //3、当扣除初始库存之后，还有数量则从入库单据中，逐一进行扣。
                                if(znDepotItem.getBasicNumber().compareTo(BigDecimal.ZERO)>0){
                                    String key = "pandian_"+tenanId+"_"+znDepotItem.getMaterialId();
                                    List<MaterialIOVo> materialIOVos =  materialMap.get(key);
                                    if(materialIOVos ==null && !nullStockMaterialIdList.contains(znDepotItem.getMaterialId())){
                                        Map<String,Object> tempMap = znProfitDetailMapper.findLastOperTimeAndInId(znProfitDetail);
                                        if(tempMap !=null){
                                            if(tempMap.containsKey("in_head_id")){
                                                if(tempMap.get("in_head_id") !=null){
                                                    queryParam.getParams().put("gtId",Long.valueOf(tempMap.get("in_head_id").toString()));
                                                }
                                            }
                                        }
                                        queryParam.setType("入库");
//                                queryParam.setSubType("采购");
                                        queryParam.setStatus("2");//已入库
                                        queryParam.getParams().put("materialId",znDepotItem.getMaterialId());
                                        queryParam.getParams().put("depotId",znDepotItem.getDepotId());
                                        materialIOVos =  znDepotHeadMapper.selectMaterialPurchaseInList(queryParam);
                                    }
                                    if(materialIOVos == null ){
//                            System.out.println("库存不足订单："+JSON.toJSONString(znDepotHead));
//                            System.out.println("库存不足商品信息："+JSON.toJSONString(znDepotItem));
                                        ZnProfitHistory znProfitHistory = new ZnProfitHistory();
                                        znProfitHistory.setId(profitId);
                                        znProfitHistory.setState(2);
                                        znProfitHistory.setResult("商品："+znDepotItem.getMaterialName()+"("+znDepotItem.getBarCode()+"）库存不足，请先采购再重新计算");
                                        znProfitHistoryMapper.updateZnProfitHistory(znProfitHistory);
                                        Thread.currentThread().interrupt();
                                        System.out.println(threadName+"已中断1");
                                        flag = false;
                                        break;
                                        //                        return AjaxResult.error("商品："+znDepotItem.getMaterialName()+"("+znDepotItem.getBarCode()+"）库存不足，请先采购再继续计算");
                                    }else{
                                        Double orderNumber = znDepotItem.getBasicNumber().doubleValue();
                                        if (orderNumber > 0 ) {
//                                if (orderNumber > 0 ) {
                                            int nextIndex  = 0;
                                            for (int i=0;i<materialIOVos.size();i++){
                                                znProfitDetail = new ZnProfitDetail();
                                                znProfitDetail.setType(0);
                                                znProfitDetail.setProfitId(profitId);
                                                znProfitDetail.setTenantId(tenanId);
                                                znProfitDetail.setDepotId(znDepotItem.getDepotId());
                                                znProfitDetail.setCustomerId(znDepotHead.getOrganId());
                                                znProfitDetail.setMaterialId(znDepotItem.getMaterialId());
                                                znProfitDetail.setMaterialExtendId(znDepotItem.getMaterialExtendId());
                                                znProfitDetail.setOutHeadId(znDepotHead.getId());
                                                znProfitDetail.setOutOperTime(znDepotHead.getOperTime());
                                                znProfitDetail.setOutItemId(znDepotItem.getId());
                                                MaterialIOVo materialIOVo = materialIOVos.get(i);
                                                orderNumber = orderNumber - materialIOVo.getBasicNumber().doubleValue();
                                                if(orderNumber <= 0 ){
                                                    znProfitDetail.setInHeadId(materialIOVo.getInHeadId());
                                                    znProfitDetail.setInItemId(materialIOVo.getInItemId());
                                                    if(orderNumber==0){
                                                        znProfitDetail.setBasicNumber(materialIOVo.getBasicNumber());
                                                        nextIndex = i+1;
                                                    }else{//当商品的数量过多，修改为多余的数量
                                                        nextIndex = i;
                                                        znProfitDetail.setBasicNumber(materialIOVo.getBasicNumber().subtract(new BigDecimal(orderNumber)));
                                                        materialIOVo.setBasicNumber(new BigDecimal(orderNumber).abs());
                                                    }
                                                    znProfitDetail.setOutPrice(znDepotItem.getUnitPrice().multiply(znProfitDetail.getBasicNumber()));
                                                    znProfitDetail.setInPrice(znProfitDetail.getBasicNumber().multiply(materialIOVo.getUnitPrice()));
                                                    znProfitDetail.setProfit(znProfitDetail.getOutPrice().subtract(znProfitDetail.getInPrice()));
                                                    dataList.add(znProfitDetail);
                                                    saveKey.add(znProfitDetail.getOutHeadId()+"-"+znProfitDetail.getOutItemId());
                                                    break;
                                                }else{
                                                    if(i<materialIOVos.size()){
                                                        znProfitDetail.setBasicNumber(materialIOVo.getBasicNumber());
                                                        znProfitDetail.setInHeadId(materialIOVo.getInHeadId());
                                                        znProfitDetail.setInItemId(materialIOVo.getInItemId());
                                                        znProfitDetail.setOutPrice(znDepotItem.getUnitPrice().multiply(znProfitDetail.getBasicNumber()));
                                                        znProfitDetail.setInPrice(materialIOVo.getBasicNumber().multiply(materialIOVo.getUnitPrice()));
                                                        znProfitDetail.setProfit(znProfitDetail.getOutPrice().subtract(znProfitDetail.getInPrice()));
                                                        dataList.add(znProfitDetail);
                                                        saveKey.add(znProfitDetail.getOutHeadId()+"-"+znProfitDetail.getOutItemId());
                                                    }else{
                                                        //                                        return AjaxResult.error("商品："+znDepotItem.getMaterialName()+"("+znDepotItem.getBarCode()+"）库存不足，请先采购再继续计算");
                                                        ZnProfitHistory znProfitHistory = new ZnProfitHistory();
                                                        znProfitHistory.setId(profitId);
                                                        znProfitHistory.setState(2);
                                                        znProfitHistory.setResult("商品："+znDepotItem.getMaterialName()+"("+znDepotItem.getBarCode()+"）库存不足，请先采购再重新计算");
                                                        znProfitHistoryMapper.updateZnProfitHistory(znProfitHistory);
                                                        Thread.currentThread().interrupt();
                                                        System.out.println("商品："+znDepotItem.getMaterialName()+"("+znDepotItem.getMaterialId()+"）库存不足，请先采购再重新计算");
//                                                System.out.println(threadName+"已中断");
                                                        flag = false;
                                                        break;
                                                    }
                                                }
                                            }
                                            List<MaterialIOVo> temp = new ArrayList<>();
                                            if(nextIndex<materialIOVos.size()){
                                                temp =  materialIOVos.subList(nextIndex,materialIOVos.size());
                                                materialMap.put(key,temp);
                                            }else{
                                                nullStockMaterialIdList.add(znDepotItem.getMaterialId());
                                                materialMap.remove(key);
                                                System.out.println(key+","+nextIndex+","+ JSON.toJSONString(materialIOVos.subList(nextIndex,materialIOVos.size())));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if(flag){
                    int batchInsertCount = 0;
                    ZnProfitHistory znProfitHistory = new ZnProfitHistory();
                    znProfitHistory.setId(profitId);
                    System.out.println(JSON.toJSONString(dataList));
                    if(dataList.size()>0){
                        batchInsertCount =  znProfitDetailMapper.batchInsertZnProfitDetail(dataList);
                        if(initStockMap.size()>0){
                            for (Map.Entry<String,ZnMaterialInitialStock> entry:initStockMap.entrySet()) {
                                ZnMaterialInitialStock znMaterialInitialStock = new ZnMaterialInitialStock();
                                znMaterialInitialStock.setId(entry.getValue().getId());
                                znMaterialInitialStock.setIsProfit("1");
                                znMaterialInitialStockMapper.updateZnMaterialInitialStock(znMaterialInitialStock);
                            }
                        }
                        znProfitHistory.setResult("利润计算成功！");
                        znProfitHistory.setState(1);
                    }else{
//                return AjaxResult.success("没有有效的计算单据！");
                        znProfitHistory.setState(2);
                        znProfitHistory.setResult("没有有效的计算单据！");
                    }
                    znProfitHistoryMapper.updateZnProfitHistory(znProfitHistory);
                    Thread.currentThread().interrupt();
                    System.out.println(threadName + " is exit");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            ZnProfitHistory znProfitHistory = new ZnProfitHistory();
            znProfitHistory.setId(profitId);
            znProfitHistory.setState(2);
            znProfitHistory.setResult("计算异常，请联系管理员");
            znProfitHistoryMapper.updateZnProfitHistory(znProfitHistory);
            throw  new ServiceException("计算异常，请联系管理员");
        }
    }
}
